str (string), int (integer), float (decimal), bool (boolean), list, and dict (dictionary).{}. This is a core part of the syntax.def keyword.Python's structure is defined by colons : and indentation. A block of code starts after a colon and is indented.
def function_name(parameter1, parameter2):
# This block is indented
result = parameter1 + parameter2
return result
if condition1:
# Do something if condition1 is true
elif condition2:
# Do something if condition2 is true
else:
# Do something if no conditions are true
# No type declaration needed
name = "Alice" # str
age = 30 # int
height = 5.5 # float
is_student = True # bool
# List (ordered, mutable)
my_list = [1, "apple", 3.14]
# Tuple (ordered, immutable)
my_tuple = (1, "apple", 3.14)
# Dictionary (unordered, key-value pairs)
my_dict = {"name": "Bob", "age": 25}
# Set (unordered, unique elements)
my_set = {1, 2, 3, 3, 4} # Becomes {1, 2, 3, 4}
+, -, *, / (division), // (floor division), % (modulus), ** (exponent).==, !=, >, <, >=, <=.and, or, not.# For loop
for item in my_list:
print(item)
# While loop
count = 0
while count < 5:
print(count)
count += 1
name = "Charlie"
age = 40
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Charlie and I am 40 years old.
import os).if __name__ == "__main__":
# Your main script execution code goes here
pass
# Traditional way
squares = []
for i in range(5):
squares.append(i * i)
# Comprehension way
squares = [i * i for i in range(5)] # [0, 1, 4, 9, 16]
python -m venv myenv
source myenv/bin/activate # On Linux/macOS
flake8 (linter) and black (formatter) in your editor to automatically enforce PEP 8 and keep your code clean.| Type | Category | Syntax Example | Mutable? |
|---|---|---|---|
int, float | Numeric | x = 10, y = 3.14 | No |
str | Sequence | s = "Hello" | No |
bool | Boolean | is_true = True | No |
list | Sequence | my_list = [1, 2, 3] | Yes |
tuple | Sequence | my_tuple = (1, 2, 3) | No |
dict | Mapping | my_dict = {'key': 'value'} | Yes |
set | Set | my_set = {1, 2, 3} | Yes |
A simple script to count the frequency of words in a given text.
def count_words(text):
"""Counts the frequency of each word in a string."""
word_counts = {}
words = text.lower().split() # Lowercase and split into words
for word in words:
# Remove punctuation for better counting
cleaned_word = word.strip(".,!?")
if cleaned_word:
word_counts[cleaned_word] = word_counts.get(cleaned_word, 0) + 1
return word_counts
if __name__ == "__main__":
sample_text = "Hello world! This is a test. Hello again."
counts = count_words(sample_text)
print("Word frequencies:")
for word, count in counts.items():
print(f"- {word}: {count}")
IndentationError: expected an indented block
: (like in an if, for, or def statement) must be indented. Ensure consistent use of spaces (PEP 8 recommends 4).SyntaxError: invalid syntax
:, mismatched parentheses () or brackets [], or an illegal character.NameError: name '...' is not defined
TypeError: can only concatenate str (not "int") to str
"Score: " + 10. Convert the non-string type using str(): "Score: " + str(10). Or better yet, use an f-string: f"Score: {10}".